﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text;
using System.Diagnostics;

using XMK.Framework.Model;
using XMK.Tadong.DataSearch.Biz;
using XMK.Tadong.Model;
using XMK.Utils;

using Lucene.Net.Documents;
using XMK.Tadong.Biz;
using Wuqi.Webdiyer;
using XMK.Tadong.Web.Language;


namespace XMK.Tadong.Web.Views.DataSearch
{
    public partial class CommonSearchView : FileExplorerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            #region Cookie记录Tab页
            string pagename = Request.CurrentExecutionFilePath.Remove(0, Request.ApplicationPath.Length + 1).Replace(".aspx", "");
            h_pagename.Value = pagename;
            if (!IsPostBack)
            {
                //如果是第一次加载，LoadCount为0.
                h_loadCount.Value = "0";

                if (!string.IsNullOrWhiteSpace(Request.Params.Get("qs_target")))
                    h_outQueryTarget.Value = Request.Params.Get("qs_target").Equals("struct") ? "2" : "1";
            }
            else
            {
                //如果不是第一次加载，LoadCount为10.
                h_loadCount.Value = "10";

                h_outQueryTarget.Value = "1";
            }
            if (Request.QueryString["savecookie"] == null || Request.QueryString["savecookie"] == "0")
            {
                h_savecookie.Value = false.ToString().ToLower();
            }
            else
            {
                h_savecookie.Value = true.ToString().ToLower();
            }


            #endregion

            if (!IsPostBack)
            {
                this.btnSearch.DataBind();
                this.btnTeamSearch.DataBind();
                h_indexPath.Value = DataSearchConfig.XMKFileIndexPath;

                //接收外部提供参数
                LuceneQuery query = null;

                //排序
                LuceneSort sort = null;

                //查询来源 0-高级检索 1-外部gis
                string qs = Request.Params.Get("qs");
                switch (qs)
                {
                    //高级检索
                    case "0":
                        //ds 起始日期
                        //de 截止日期
                        long startDate;
                        long endDate;
                        string s = Request.Params.Get("s");
                        LuceneQuery dateQuery = null;
                        if (s.Equals("2"))
                        {
                            startDate = ParseHelper.Parse<long>(
                                ParseHelper.Parse<DateTime>(Request.Params.Get("startDate")).ToString("yyyyMMddHHmmss"));
                            endDate = ParseHelper.Parse<long>(
                                ParseHelper.Parse<DateTime>(Request.Params.Get("endDate")).ToString("yyyyMMddHHmmss"));
                            dateQuery = LuceneQuery.Between("FILE_CRT_DATE_NUM", startDate, endDate);
                        }
                        else
                        {
                            string mt = Request.Params.Get("mt");
                            if (mt.Equals("1")) //最近一天
                                dateQuery = LuceneQuery.Gte("FILE_CRT_DATE_NUM",
                                    ParseHelper.Parse<long>(DateTime.Now.AddDays(-1).ToString("yyyyMMddHHmmss")));
                            else if (mt.Equals("2")) //最近一周
                                dateQuery = LuceneQuery.Gte("FILE_CRT_DATE_NUM",
                                    ParseHelper.Parse<long>(DateTime.Now.AddDays(-7).ToString("yyyyMMddHHmmss")));
                            else if (mt.Equals("3")) //最近一月
                                dateQuery = LuceneQuery.Gte("FILE_CRT_DATE_NUM",
                                    ParseHelper.Parse<long>(DateTime.Now.AddMonths(-1).ToString("yyyyMMddHHmmss")));
                            else if (mt.Equals("4")) //最近一年
                                dateQuery = LuceneQuery.Gte("FILE_CRT_DATE_NUM",
                                    ParseHelper.Parse<long>(DateTime.Now.AddYears(-1).ToString("yyyyMMddHHmmss")));
                        }

                        //psize 页面显示条数
                        //
                        AspNetPager1.PageSize = int.Parse(Request.Params.Get("psize"));

                        //查询关键词目标
                        List<string> fieldList = new List<string>();
                        if (!string.IsNullOrWhiteSpace(Request.Params.Get("ckmeta")))
                        {
                            //元数据
                            fieldList.Add("META_DATA");
                        }

                        if (!string.IsNullOrWhiteSpace(Request.Params.Get("cktit")))
                        {
                            //文件名
                            fieldList.Add("FILE_NAME");
                        }

                        if (!string.IsNullOrWhiteSpace(Request.Params.Get("ckcont")))
                        {
                            //内容
                            fieldList.Add("FILE_CONT");
                        }

                        Session["flist"] = fieldList;

                        StringBuilder sbAnd = new StringBuilder();

                        //and关键词

                        string qAndText = Request.Params.Get("qand");
                        qAndText = FilterKeyword(qAndText);
                        if (!string.IsNullOrWhiteSpace(qAndText))
                        {
                            string[] qAndArr = qAndText.Split(new char[] { ' ' },
                                StringSplitOptions.RemoveEmptyEntries);

                            foreach (var qAnd in qAndArr)
                            {
                                sbAnd.AppendFormat("+{0} ", qAnd);
                            }

                            List<LuceneQuery> andQuery = new List<LuceneQuery>();
                            string q = sbAnd.ToString();

                            foreach (var f in fieldList)
                            {
                                float boost = 1.0f;
                                if (f.Equals("FILE_NAME") || f.Equals("META_DATA"))
                                    boost = 2.0f;
                                andQuery.Add(LuceneQuery.Lk(f, q,
                                    LuceneAnalyzerType.Standard, boost));
                            }
                            query = LuceneQuery.Or(andQuery.ToArray());
                        }

                        //or关键词
                        string qORText = Request.Params.Get("qor");
                        qORText = FilterKeyword(qORText);
                        if (!string.IsNullOrWhiteSpace(qORText))
                        {
                            string[] qorArr = qORText.Split(new char[] { ' ' },
                                StringSplitOptions.RemoveEmptyEntries);
                            List<LuceneQuery> orQuery = new List<LuceneQuery>();
                            foreach (string f in fieldList)
                            {
                                float boost = 1.0f;
                                if (f.Equals("FILE_NAME") || f.Equals("META_DATA"))
                                    boost = 2.0f;
                                orQuery.Add(LuceneQuery.Lk(f, qORText, LuceneAnalyzerType.Standard, boost));
                            }
                            query = LuceneQuery.And(query, LuceneQuery.Or(orQuery.ToArray()));

                            sbAnd.Append(" ");
                            sbAnd.Append(string.Join("|", qorArr));
                        }

                        //日期
                        if (dateQuery != null)
                            query = LuceneQuery.And(query, dateQuery);

                        txtKeyword.Text = sbAnd.ToString().Trim();

                        // 排序
                        sort = new LuceneSort();
                        int sortBy = int.Parse(Request.Params.Get("sortby"));
                        string sortField = "DOWN_AMOUNT";
                        if (sortBy == 2)
                        {
                            sortField = "FILE_CRT_DATE_NUM";
                            sort.AddDesc(sortField, LuceneSortType.LONG);
                        }
                        else
                        {
                            sort.AddDesc(sortField, LuceneSortType.INT);
                        }

                        Session["sort"] = sort;

                        //时间

                        break;
                    //外部gis
                    case "1":

                        #region 外部GIS接口
                        h_outQueryTarget.Value = "1";//默认非结构化搜索

                        var queryFieldList = new List<string>();

                        if (Request.Params.Get("act").Equals("ysj"))
                        {
                            ///非结构化搜索
                            //元数据+标题
                            queryFieldList.Add("FILE_NAME");
                            queryFieldList.Add("META_DATA");
                        }
                        else if (Request.Params.Get("act").Equals("qw"))
                        {
                            ///非结构化搜索
                            //元数据+标题+全文
                            queryFieldList.Add("FILE_NAME");
                            queryFieldList.Add("META_DATA");
                            queryFieldList.Add("FILE_CONT");
                        }
                        else
                        {   ///结构化搜索
                            h_outQueryTarget.Value = "2";
                        }
                        Session["flist"] = queryFieldList;
                        txtKeyword.Text = FilterKeyword(Request.Params.Get("z").Trim());
                        Session["sort"] = sort;

                        List<LuceneQuery> tempQuery = new List<LuceneQuery>();

                        foreach (var f in queryFieldList)
                        {
                            float boost = 1.0f;
                            if (f.Equals("FILE_NAME") || f.Equals("META_DATA"))
                                boost = 2.0f;
                            tempQuery.Add(LuceneQuery.Lk(f, txtKeyword.Text,
                                LuceneAnalyzerType.Standard, boost));
                        }
                        query = LuceneQuery.Or(tempQuery.ToArray());

                        #endregion

                        break;
                    default:

                        //查询字段
                        Session["flist"] = new List<string>
                        {
                            "FILE_NAME",
                            "FILE_CONT"
                        };

                        //
                        //默认根据下载次数排序
                        //2014年11月16日 14:57:20
                        //
                        sort = new LuceneSort();
                        sort.AddDesc("DOWN_AMOUNT", LuceneSortType.INT);
                        
                        //排序对象
                        Session["sort"] = sort;

                        break;
                }

                if (query == null)
                {
                    ExecuteSearch();
                }
                else
                {
                    //
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    PageInfo pageinfo = new PageInfo();
                    pageinfo.PageSize = this.AspNetPager1.PageSize;
                    pageinfo.CurrentPage = this.AspNetPager1.CurrentPageIndex;
                    FileSearchBiz fileBiz = new FileSearchBiz();
                    ResponseInfo resInfo = fileBiz.SearchFileList(sort,
                        query, pageinfo, h_indexPath.Value);
                    RenderData(sw, resInfo);
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

            AspNetPager1.CurrentPageIndex = 1;
            //
            Button btn = sender as Button;
            if (btn.CommandArgument.ToString().ToLower().Equals("team"))
            {
                h_indexPath.Value = DataSearchConfig.TeamFileIndexPath;
                h_spaceType.Value = "20";
            }
            else
            {
                h_indexPath.Value = DataSearchConfig.XMKFileIndexPath;
                h_spaceType.Value = "30";
            }
            ExecuteSearch();
        }

        private void ExecuteSearch()
        {
            try
            {
                Stopwatch watch = new Stopwatch();

                watch.Start();

                ResponseInfo resInfo = null;
                FileSearchBiz biz = new FileSearchBiz();

                LuceneQuery query = null;
                LuceneSort sort = null;
                if (string.IsNullOrWhiteSpace(txtKeyword.Text.Trim()))
                {
                    query = LuceneQuery.Gt("FILE_CRT_DATE_NUM", (long)1);
                }
                else
                {
                    string q = txtKeyword.Text.Trim();
                    q = FilterKeyword(q);
                    q = q.Replace(" ", " AND ");
                    List<string> fieldList = Session["flist"] as List<string>;
                    List<LuceneQuery> queryList = new List<LuceneQuery>();  
                    foreach (var item in fieldList)
                    {
                        queryList.Add(LuceneQuery.Lk(item, q, LuceneAnalyzerType.Standard));
                    }
                    query = LuceneQuery.Or(queryList.ToArray());

                    sort = Session["sort"] as LuceneSort;
                }
                PageInfo pageInfo = new PageInfo();
                pageInfo.CurrentPage = this.AspNetPager1.CurrentPageIndex;
                pageInfo.PageSize = this.AspNetPager1.PageSize;
                resInfo = biz.SearchFileList(sort, query, pageInfo, h_indexPath.Value);
                RenderData(watch, resInfo);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogType.Error, ex.ToString());
            }

        }

        private void RenderData(Stopwatch watch, ResponseInfo resInfo)
        {
            XMKLogInfo logModel = new XMKLogInfo();
            logModel.Keyword = txtKeyword.Text.Trim();
            logModel.LogDesc = string.Format("【{0}】【{1}】query keywords {2}",
                LoginUserBiz.LoginUserName(), LoginUserBiz.LoginUserAccount(), logModel.Keyword);
            logModel.OperateTime = DateTime.Now;
            logModel.OperateType = LogOperateType.Search;
            logModel.UserId = LoginUserBiz.LoginUserID();
            logModel.IP = Request.ServerVariables["REMOTE_ADDR"].Equals("::1") ? "127.0.0.1" : Request.ServerVariables["REMOTE_ADDR"];
            XMKLogBiz.WriteLog(logModel);

            if (!string.IsNullOrWhiteSpace(resInfo.ErrMsg))
            {
                divContainer.InnerHtml = resInfo.ErrMsg;
                return;
            }

            int[] hits = resInfo.Data as int[];

            if (hits == null || hits.Count() == 0)
            {
                AspNetPager1.RecordCount = 0;
                StringBuilder reportBuilder = new StringBuilder();

                reportBuilder.AppendLine("<div id='content_left' >");

                //性能报告

                searchCount.InnerHtml = string.Format("<span id='spanSearchResult' style='color:black;font-weight:bold;'>" + lang.Get("Find relevant results") + ":{0}," + lang.Get("Time consuming") + "：{1}" + lang.Get("Millisecond") + "</span>",
                    0, watch.ElapsedMilliseconds);
                watch.Stop();

                //reportBuilder.Append("没有搜索到任何数据");
                reportBuilder.Append(lang.Get("No search data"));
                reportBuilder.AppendLine("</div>");

                divContainer.InnerHtml = reportBuilder.ToString();

                return;
            }
            AspNetPager1.RecordCount = (int)resInfo.Page.Records;

            StringBuilder contentBuilder = new StringBuilder();

            contentBuilder.AppendLine("<div id='content_left' >");

            //性能报告
            searchCount.InnerHtml = string.Format("<span id='spanSearchResult' style='color:black;font-weight:bold;'>" + lang.Get("Find relevant results") + "{0}," + lang.Get("Time consuming") + "：{1}" + lang.Get("Millisecond") + "</span>",
                resInfo.Page.Records, watch.ElapsedMilliseconds);
            Debug.WriteLine(string.Format(lang.Get("Find relevant results") + ":{0}" + lang.Get("Time consuming") + "：{1}" + lang.Get("Millisecond"),
                resInfo.Page.Records, watch.ElapsedMilliseconds));
            watch.Stop();

            watch = new Stopwatch();
            watch.Start();

            LuceneAccess luceneHelper = new LuceneAccess(h_indexPath.Value);
            LuceneQuery query = null;

            if (!string.IsNullOrWhiteSpace(txtKeyword.Text.Trim()))
            {
                string q = txtKeyword.Text.Trim();
                q = FilterKeyword(q);
                List<string> fieldList = Session["flist"] as List<string>;
                if (fieldList != null && fieldList.Count > 0)
                {
                    List<LuceneQuery> queryList = new List<LuceneQuery>();
                    foreach (var item in fieldList)
                    {
                        queryList.Add(LuceneQuery.Lk(item,
                            q
                            , LuceneAnalyzerType.Standard));
                    }
                    query = LuceneQuery.And(queryList.ToArray());
                }

            }

            ///lucene自带高亮，选取自动截取，截取高亮词周围文字
            //Dictionary<int, string> fileNameHighDict =
            //    luceneHelper.GetHighLightDict(query, hits.ToList(), "FILE_NAME",
            //    new List<string> { "<font color=\"red\" >" },
            //    new List<string> { "</font>" }, 100);

            ///盘古分词，不截取
            Dictionary<int, string> fileNameHighDict =
                luceneHelper.GetHighLightDictPangu(query, hits.ToList(), "FILE_NAME", "<font color=\"red\" >", "</font>");

            Dictionary<int, string> fileContHighDict =
                luceneHelper.GetHighLightDict(query, hits.ToList(), "FILE_CONT",
                new List<string> { "<font color=\"red\" >" },
                new List<string> { "</font>" }, 100);

            foreach (int docId in hits)
            {
                Document doc = luceneHelper.GetIndexSearcher().Doc(docId);

                contentBuilder.AppendLine("<div class='ec_pp_top' >");

                //标题部分
                contentBuilder.AppendLine("<div class='ec_title' >");
                contentBuilder.AppendLine("<h3 class='t ec_nowrap' >");
                string file_ext = doc.Get("FILE_NAME").Substring(doc.Get("FILE_NAME").LastIndexOf(".")+1);
                contentBuilder.AppendLine(string.Format("<img src='{0}' />", GetFileIconPath(file_ext)));

                string fileName = doc.Get("FILE_NAME");
                string fileNameHigh = fileNameHighDict.ContainsKey(docId) ? fileNameHighDict[docId] : string.Empty;
                string fileNameTmp = fileName;
                if (query == null||fileNameHigh == "")
                {
                    if (fileName.Length > 45)
                    {
                        fileName = fileName.Substring(0, 43) + "..." ;
                    }
                    contentBuilder.AppendFormat("<a id={1} title={2} >{0} </a></h3></div>",
                    fileName, doc.Get("FILE_ID"), fileNameTmp);
                }
                else
                {
                   
                     contentBuilder.AppendFormat("<a id={1} title={2} >{0} </a></h3></div>",
                     fileNameHigh, doc.Get("FILE_ID"), fileNameTmp);
                  

                }

                //内容部分
                string fileCont = doc.Get("FILE_CONT");
                int fileContLen = fileCont.Length;
                string fileContHigh = fileContHighDict.ContainsKey(docId) ? fileContHighDict[docId] : string.Empty;

                if (!string.IsNullOrWhiteSpace(fileCont))
                {
                    fileCont = fileCont.Substring(0, fileContLen > 120 ? 120 : fileContLen);
                    contentBuilder.AppendFormat("<div class='ec_desc ec_font_small' >{0}</div>",
                        string.IsNullOrWhiteSpace(fileContHigh) ? fileCont : fileContHigh);
                }
                else
                {
                    //contentBuilder.AppendFormat("<div class='ec_desc ec_font_small' >{0}</div>",
                    //     lang.Get("The content of a document is empty"));

                    contentBuilder.AppendFormat("<div class='ec_desc ec_font_small' >{0}</div>",
                        doc.Get("TEAM_NAME") + "  " + doc.Get("DEST_OBJ") + "  " + doc.Get("BIZ_OBJ"));
                }

                //条目结尾
                contentBuilder.AppendLine("<div class='ec_meta ec_font_small' >");
                int i = 0;

                //创建时间
                string fileCreateDate = doc.Get("FILE_CRT_DATE");
                if (!string.IsNullOrWhiteSpace(fileCreateDate))
                {
                    i++;
                    contentBuilder.AppendFormat("<span  ><font >{0}</font> </span>",
                        ParseHelper.Parse<DateTime>(fileCreateDate).ToString("yyyy-MM-dd"));
                }

                //课题组
                string teamName = doc.Get("TEAM_NAME");
                if (!string.IsNullOrWhiteSpace(teamName))
                {
                    if (i > 0)
                    {
                        contentBuilder.Append("<span style='margin:5px 1px ;'> | </span>");
                    }
                    contentBuilder.AppendFormat("<span  >" + lang.Get("Workgroup") + "：<font >{0}</font> </span>", teamName);

                    i++;
                }

                //目标
                string destName = doc.Get("DEST_OBJ");
                if (!string.IsNullOrWhiteSpace(destName))
                {
                    if (i > 0)
                    {
                        contentBuilder.Append("<span style='margin:5px 1px ;'> | </span>");
                    }
                    contentBuilder.AppendFormat("<span  ><font >{0}</font> </span>", destName);

                    i++;
                }

                //业务
                string bizName = doc.Get("BIZ_OBJ");
                if (!string.IsNullOrWhiteSpace(bizName))
                {
                    if (i > 0)
                    {
                        contentBuilder.Append("<span style='margin:5px 1px ;'> | </span>");
                    }
                    contentBuilder.AppendFormat("<span  > "+lang.Get("Millisecond")+"<font >{0}</font> </span>", bizName);

                    i++;
                }

                //下载次数
                string downAmount = doc.Get("DOWN_AMOUNT");
                if (!string.IsNullOrWhiteSpace(downAmount))
                {
                    if (i > 0)
                    {
                        contentBuilder.Append("<span style='margin:5px 1px ;'> | </span>");
                    }
                    contentBuilder.AppendFormat("<span  > "+lang.Get("Amount of Downloads")+"：<font >{0}</font> </span>", downAmount);

                    i++;
                }

                //文件大小
                string fileSize = doc.Get("FILE_SIZE");
                if (!string.IsNullOrWhiteSpace(fileSize))
                {
                    if (i > 0)
                    {
                        contentBuilder.Append("<span style='margin:5px 1px ;'> | </span>");
                    }
                    contentBuilder.AppendFormat("<span  ><font >{0}</font> </span>", fileSize);

                    i++;
                }

                //作者
                string fileAuthor = doc.Get("FILE_AUTHOR");
                if (!string.IsNullOrWhiteSpace(fileAuthor))
                {
                    if (i > 0)
                    {
                        contentBuilder.Append("<span style='margin:5px 1px ;'> | </span>");
                    }
                    contentBuilder.AppendFormat("<span >"+lang.Get("Author")+":<font >{0}</font> </span>", fileAuthor);

                    i++;
                }

                contentBuilder.AppendLine("</div>");

                contentBuilder.AppendLine("</div>");
            }

            contentBuilder.AppendLine("</div>");

            divContainer.InnerHtml = contentBuilder.ToString();

            Debug.WriteLine(lang.Get("Highligh")+lang.Get("Time consuming") + watch.ElapsedMilliseconds +lang.Get("Millisecond"));
        }

        protected void AspNetPager1_PageChanged(object sender, PageChangingEventArgs e)
        {
            this.AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            ExecuteSearch();
        }

        protected string GetFileIconPath(string fileType)
        {
            EXTBiz biz = new EXTBiz();
            ExtTypeinfo extcode = biz.getExtCodeByExtent(fileType);
            string path = "";
            if (extcode != null)
            {
                path = "../../WebFileExplorer/images/ico/exttype/" + extcode.PIC_NAME;
            }
            else
            {
                path = "../../WebFileExplorer/images/ico/exttype/130901108129_2486.png";
            }
            //switch ((FileType)fileType)
            //{
            //    case FileType.Excel:
            //        path = "../../weblib/skins/images/officeicon/excel.png";
            //        break;
            //    case FileType.Word:
            //        path = "../../weblib/skins/images/officeicon/word.png";
            //        break;
            //    case FileType.TXT:
            //        path = "../../weblib/skins/images/officeicon/text.png";
            //        break;
            //    case FileType.PPT:
            //        path = "../../weblib/skins/images/officeicon/ppt.png";
            //        break;
            //    case FileType.PDF:
            //    default:
            //        path = "../../weblib/skins/images/officeicon/pdf.png";
            //        break;
            //}
            return path;
        }

    }
}